<template>
  <div class="page-container">
    <div class="flex justify-between items-center">
      <div>
        <h1 class="page-title">个人中心</h1>
        <div class="breadcrumb-container">
          <ul>
            <li><a @click="router.push('/')">首页</a></li>
            <li>个人中心</li>
          </ul>
        </div>
      </div>
    </div>

    <div class="card-container">
      <!-- 个人信息 -->
      <div class="card-content lg:col-span-2">
        <div class="card-body-custom">
          <h2 class="section-title">个人信息</h2>
          <div class="form-group">
            <div class="input-group">
              <label class="label">
                <span class="input-label">头像</span>
              </label>
              <div class="flex items-center gap-4">
                <div class="avatar">
                  <div class="w-24 rounded-full">
                    <img :src="formData.avatar" alt="用户头像" />
                  </div>
                </div>
                <button class="btn btn-outline" @click="uploadAvatar">更换头像</button>
              </div>
            </div>
            <div class="input-group">
              <label class="label">
                <span class="input-label">用户名</span>
                <span class="input-error-text">*</span>
              </label>
              <input
                type="text"
                v-model="formData.username"
                placeholder="请输入用户名"
                class="input input-bordered w-full"
                :class="{ 'input-error': errors.username }"
                @blur="validateField('username')"
              />
              <label class="label" v-if="errors.username">
                <span class="input-error-text">{{ errors.username }}</span>
              </label>
            </div>
            <div class="input-group">
              <label class="label">
                <span class="input-label">昵称</span>
                <span class="input-error-text">*</span>
              </label>
              <input
                type="text"
                v-model="formData.nickname"
                placeholder="请输入昵称"
                class="input input-bordered w-full"
                :class="{ 'input-error': errors.nickname }"
                @blur="validateField('nickname')"
              />
              <label class="label" v-if="errors.nickname">
                <span class="input-error-text">{{ errors.nickname }}</span>
              </label>
            </div>
            <div class="input-group">
              <label class="label">
                <span class="input-label">邮箱</span>
                <span class="input-error-text">*</span>
              </label>
              <input
                type="email"
                v-model="formData.email"
                placeholder="请输入邮箱"
                class="input input-bordered w-full"
                :class="{ 'input-error': errors.email }"
                @blur="validateField('email')"
              />
              <label class="label" v-if="errors.email">
                <span class="input-error-text">{{ errors.email }}</span>
              </label>
            </div>
            <div class="input-group">
              <label class="label">
                <span class="input-label">手机号码</span>
                <span class="input-error-text">*</span>
              </label>
              <input
                type="tel"
                v-model="formData.phone"
                placeholder="请输入手机号码"
                class="input input-bordered w-full"
                :class="{ 'input-error': errors.phone }"
                @blur="validateField('phone')"
              />
              <label class="label" v-if="errors.phone">
                <span class="input-error-text">{{ errors.phone }}</span>
              </label>
            </div>
          </div>
          <div class="flex justify-end mt-6">
            <button class="btn btn-primary" @click="saveProfile" :disabled="isSaving">
              <span v-if="isSaving" class="loading loading-spinner"></span>
              {{ isSaving ? '保存中...' : '保存修改' }}
            </button>
          </div>
        </div>
      </div>

      <!-- 账号安全 -->
      <div class="space-y-6">
        <div class="card-content">
          <div class="card-body-custom">
            <h2 class="section-title">账号安全</h2>
            <div class="space-y-4">
              <div class="flex items-center justify-between">
                <div>
                  <div class="font-medium">登录密码</div>
                  <div class="text-sm text-base-content/60">定期修改密码可以保护账号安全</div>
                </div>
                <button class="btn btn-outline btn-sm" @click="showPasswordModal = true">修改密码</button>
              </div>
              <div class="flex items-center justify-between">
                <div>
                  <div class="font-medium">两步验证</div>
                  <div class="text-sm text-base-content/60">开启后需要额外验证才能登录</div>
                </div>
                <input type="checkbox" v-model="security.twoFactor" class="toggle" />
              </div>
              <div class="flex items-center justify-between">
                <div>
                  <div class="font-medium">登录通知</div>
                  <div class="text-sm text-base-content/60">异地登录时发送邮件通知</div>
                </div>
                <input type="checkbox" v-model="security.loginNotification" class="toggle" />
              </div>
            </div>
          </div>
        </div>

        <div class="card-content">
          <div class="card-body-custom">
            <h2 class="section-title">登录历史</h2>
            <div class="space-y-4">
              <div v-for="log in loginLogs" :key="log.id" class="flex items-center justify-between">
                <div>
                  <div class="font-medium">{{ log.location }}</div>
                  <div class="text-sm text-base-content/60">{{ log.time }}</div>
                </div>
                <div class="badge" :class="log.status === 'success' ? 'badge-success' : 'badge-error'">
                  {{ log.status === 'success' ? '成功' : '失败' }}
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 修改密码弹窗 -->
    <dialog :class="{ 'modal': true, 'modal-open': showPasswordModal }">
      <div class="modal-box">
        <h3 class="font-bold text-lg">修改密码</h3>
        <div class="py-4 space-y-4">
          <div class="form-control">
            <label class="label">
              <span class="label-text">当前密码</span>
            </label>
            <input
              type="password"
              v-model="passwordForm.oldPassword"
              placeholder="请输入当前密码"
              class="input input-bordered"
              :class="{ 'input-error': passwordErrors.oldPassword }"
            />
            <label class="label" v-if="passwordErrors.oldPassword">
              <span class="label-text-alt text-error">{{ passwordErrors.oldPassword }}</span>
            </label>
          </div>
          <div class="form-control">
            <label class="label">
              <span class="label-text">新密码</span>
            </label>
            <input
              type="password"
              v-model="passwordForm.newPassword"
              placeholder="请输入新密码"
              class="input input-bordered"
              :class="{ 'input-error': passwordErrors.newPassword }"
            />
            <label class="label" v-if="passwordErrors.newPassword">
              <span class="label-text-alt text-error">{{ passwordErrors.newPassword }}</span>
            </label>
          </div>
          <div class="form-control">
            <label class="label">
              <span class="label-text">确认新密码</span>
            </label>
            <input
              type="password"
              v-model="passwordForm.confirmPassword"
              placeholder="请再次输入新密码"
              class="input input-bordered"
              :class="{ 'input-error': passwordErrors.confirmPassword }"
            />
            <label class="label" v-if="passwordErrors.confirmPassword">
              <span class="label-text-alt text-error">{{ passwordErrors.confirmPassword }}</span>
            </label>
          </div>
        </div>
        <div class="modal-action">
          <button class="btn" @click="showPasswordModal = false">取消</button>
          <button class="btn btn-primary" @click="changePassword" :disabled="isChangingPassword">
            <span v-if="isChangingPassword" class="loading loading-spinner"></span>
            {{ isChangingPassword ? '修改中...' : '确认修改' }}
          </button>
        </div>
      </div>
      <form method="dialog" class="modal-backdrop">
        <button>关闭</button>
      </form>
    </dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive } from 'vue'
import { useRouter } from 'vue-router'

const router = useRouter()
const isSaving = ref(false)
const showPasswordModal = ref(false)
const isChangingPassword = ref(false)

interface FormData {
  avatar: string
  username: string
  nickname: string
  email: string
  phone: string
}

const formData = reactive<FormData>({
  avatar: 'https://api.dicebear.com/7.x/avataaars/svg?seed=Felix',
  username: 'admin',
  nickname: '管理员',
  email: 'admin@example.com',
  phone: '13800138000',
})

interface FormErrors {
  username: string
  nickname: string
  email: string
  phone: string
}

const errors = reactive<FormErrors>({
  username: '',
  nickname: '',
  email: '',
  phone: '',
})

interface PasswordForm {
  oldPassword: string
  newPassword: string
  confirmPassword: string
}

const passwordForm = reactive<PasswordForm>({
  oldPassword: '',
  newPassword: '',
  confirmPassword: '',
})

interface PasswordErrors {
  oldPassword: string
  newPassword: string
  confirmPassword: string
}

const passwordErrors = reactive<PasswordErrors>({
  oldPassword: '',
  newPassword: '',
  confirmPassword: '',
})

const security = reactive({
  twoFactor: false,
  loginNotification: true,
})

const loginLogs = ref([
  {
    id: 1,
    location: '广东省广州市',
    time: '2024-03-09 10:30:00',
    status: 'success',
  },
  {
    id: 2,
    location: '北京市朝阳区',
    time: '2024-03-08 14:20:00',
    status: 'success',
  },
  {
    id: 3,
    location: '浙江省杭州市',
    time: '2024-03-07 09:15:00',
    status: 'failed',
  },
])

const validateField = (field: keyof FormErrors) => {
  let isValid = true

  switch (field) {
    case 'username':
      if (!formData.username) {
        errors.username = '请输入用户名'
        isValid = false
      } else if (formData.username.length < 3) {
        errors.username = '用户名长度不能小于3个字符'
        isValid = false
      } else {
        errors.username = ''
      }
      break
    case 'nickname':
      if (!formData.nickname) {
        errors.nickname = '请输入昵称'
        isValid = false
      } else {
        errors.nickname = ''
      }
      break
    case 'email':
      if (!formData.email) {
        errors.email = '请输入邮箱'
        isValid = false
      } else if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(formData.email)) {
        errors.email = '请输入正确的邮箱格式'
        isValid = false
      } else {
        errors.email = ''
      }
      break
    case 'phone':
      if (!formData.phone) {
        errors.phone = '请输入手机号码'
        isValid = false
      } else if (!/^1[3-9]\d{9}$/.test(formData.phone)) {
        errors.phone = '请输入正确的手机号码'
        isValid = false
      } else {
        errors.phone = ''
      }
      break
  }

  return isValid
}

const validateForm = () => {
  let isValid = true
  for (const field in errors) {
    if (!validateField(field as keyof FormErrors)) {
      isValid = false
    }
  }
  return isValid
}

const saveProfile = async () => {
  if (!validateForm()) {
    return
  }

  isSaving.value = true
  try {
    // TODO: 调用API保存个人信息
    await new Promise((resolve) => setTimeout(resolve, 1000))
    // 显示成功提示
  } catch (error) {
    // 显示错误提示
    console.error('保存个人信息失败:', error)
  } finally {
    isSaving.value = false
  }
}

const uploadAvatar = () => {
  // TODO: 实现头像上传
}

const validatePasswordForm = () => {
  let isValid = true

  if (!passwordForm.oldPassword) {
    passwordErrors.oldPassword = '请输入当前密码'
    isValid = false
  } else {
    passwordErrors.oldPassword = ''
  }

  if (!passwordForm.newPassword) {
    passwordErrors.newPassword = '请输入新密码'
    isValid = false
  } else if (passwordForm.newPassword.length < 6) {
    passwordErrors.newPassword = '新密码长度不能小于6个字符'
    isValid = false
  } else {
    passwordErrors.newPassword = ''
  }

  if (!passwordForm.confirmPassword) {
    passwordErrors.confirmPassword = '请确认新密码'
    isValid = false
  } else if (passwordForm.confirmPassword !== passwordForm.newPassword) {
    passwordErrors.confirmPassword = '两次输入的密码不一致'
    isValid = false
  } else {
    passwordErrors.confirmPassword = ''
  }

  return isValid
}

const changePassword = async () => {
  if (!validatePasswordForm()) {
    return
  }

  isChangingPassword.value = true
  try {
    // TODO: 调用API修改密码
    await new Promise((resolve) => setTimeout(resolve, 1000))
    showPasswordModal.value = false
    // 显示成功提示
  } catch (error) {
    // 显示错误提示
    console.error('修改密码失败:', error)
  } finally {
    isChangingPassword.value = false
  }
}
</script>

<style scoped>
.modal-box {
  @apply max-w-md;
}
</style>
